package com.zhku.shoppingspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhku.shoppingspringboot.common.BaseContext;
import com.zhku.shoppingspringboot.common.R;
import com.zhku.shoppingspringboot.mapper.*;
import com.zhku.shoppingspringboot.pojo.dto.AllSelectedDTO;
import com.zhku.shoppingspringboot.pojo.dto.MergeCartDTO;
import com.zhku.shoppingspringboot.pojo.entity.*;
import com.zhku.shoppingspringboot.pojo.vo.ShowShopCartsVO;
import com.zhku.shoppingspringboot.service.IShopCartService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.zhku.shoppingspringboot.common.ResultCode.ERROR;
import static com.zhku.shoppingspringboot.common.ResultCode.NO_EXIST;

/**
 * @author hwy
 * @date 2024-12-27 08:28
 */
@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper,ShopCart> implements IShopCartService{

    @Resource
    private SkusMapper skusMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private SpecsMapper specsMapper;
    @Resource
    private DetailsMapper detailsMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> mergeCart(List<MergeCartDTO> mergeCartDTOs) {
        if(CollUtil.isEmpty(mergeCartDTOs)){
            return R.success("合并成功");
        }

        List<Long> skuIds = mergeCartDTOs.stream().map(mergeCartDTO -> {return mergeCartDTO.getSkuId();}).collect(Collectors.toList());
            //查询商品sku信息
            LambdaQueryWrapper<Skus> skusLambdaQueryWrapper = new LambdaQueryWrapper<>();
            skusLambdaQueryWrapper.in(Skus::getSkuCode, skuIds);
            List<Skus> skuses = skusMapper.selectList(skusLambdaQueryWrapper);
            HashMap<Long, Skus> skuesHashMap = MapUtil.newHashMap();
            if(CollUtil.isEmpty(skuses)){
                return R.error(NO_EXIST,"数据不存在");
            }
            //查询商品属性
        List<Long> goodsIds = skuses.stream().map(Skus::getGoodsId).collect(Collectors.toList());
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(Details::getGoodsId,goodsIds);
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);
        for(Skus skus : skuses){
                skuesHashMap.put(skus.getId(),skus);
            }

        List<ShopCart> shopCarts = mergeCartDTOs.stream().map(mergeCartDTO -> {
            ShopCart shopCart = BeanUtil.copyProperties(mergeCartDTO, ShopCart.class);
            shopCart.setUserId(BaseContext.getCurrentId());
            //设置商品sku相关信息
            if(skuesHashMap.containsKey(mergeCartDTO.getSkuId())){
                Skus skus = skuesHashMap.get(mergeCartDTO.getSkuId());
                shopCart.setNowOriginalPrice(skus.getPrice());
                shopCart.setNowPrice(skus.getPrice());
                shopCart.setGoodsId(skus.getGoodsId());
                //设置商品属性
                for(Details details1 : details){
                    if(details1.getGoodsId() == skus.getGoodsId()){
                        String attrsText = shopCart.getAttrsText();
                        String newAttrsText = StrUtil.join(attrsText, details1.getName() + " " + details1.getValue() + " ");
                        shopCart.setAttrsText(newAttrsText);
                    }
                }
            }
            return shopCart;
        }).collect(Collectors.toList());
            if(saveBatch(shopCarts)){
                return R.success("合并成功");
            }else {
                return R.error(ERROR,"合并失败");
            }

    }

    @Override
    public List<ShowShopCartsVO> showShopCart() {
        //搜索当前用户购物车数据
        List<ShopCart> shopCarts = this.lambdaQuery().eq(ShopCart::getUserId, BaseContext.getCurrentId()).list();
        if(CollUtil.isEmpty(shopCarts)){
            return CollUtil.newArrayList();
        }

        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<Goods>();
        LambdaQueryWrapper<Skus> skusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取sku表数据
        List<Long> skuIds = shopCarts.stream().map(ShopCart::getSkuId).collect(Collectors.toList());
        skusLambdaQueryWrapper.in(Skus::getId,skuIds);
        List<Skus> skuses = skusMapper.selectList(skusLambdaQueryWrapper);

        //获取商品表信息
        goodsLambdaQueryWrapper.in(CollUtil.isNotEmpty(skuses),Goods::getId,skuses.stream().map(Skus::getGoodsId).collect(Collectors.toList()));
        List<Goods> goods = goodsMapper.selectList(goodsLambdaQueryWrapper);
        if(CollUtil.isEmpty(goods)){
            return CollUtil.newArrayList();
        }
        HashMap<Long, Goods> goodsHashMap = MapUtil.newHashMap();
        for(Goods goods1 : goods){
            goodsHashMap.put(goods1.getId(),goods1);
        }
        List<Long> goodsIds = goods.stream().map(Goods::getId).collect(Collectors.toList());
        //查出所有商品规格id
        ArrayList<Integer> specs = CollUtil.newArrayList();
        //转换为HashMap
        HashMap<Long, Skus> specHashmap = MapUtil.newHashMap();
        for(Skus skus : skuses){
            String specsIdList = skus.getSpecsIdList();
            List<Integer> bean = JSONUtil.toBean(specsIdList, new TypeReference<List<Integer>>() {
            }, false);
            CollUtil.addAll(specs,bean);
            specHashmap.put(skus.getId(),skus);
        }

        //设置商品属性
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(Details::getGoodsId,goodsIds);
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);
        HashMap<Long, String> detailHashMap = MapUtil.newHashMap();
        for(Details details1 : details){
            String join = StrUtil.join(detailHashMap.get(details1.getGoodsId()), details1.getName() + " " + details1.getValue());
            detailHashMap.put(details1.getGoodsId(),join);
        }
        //查出所有商品规格
        LambdaQueryWrapper<Specs> specsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        specsLambdaQueryWrapper.in(CollUtil.isNotEmpty(specs),Specs::getSpecsId,specs);
        List<Specs> specses = specsMapper.selectList(specsLambdaQueryWrapper);
        //转换为map方便查找
        HashMap<Long, Specs> specsHashMap = MapUtil.newHashMap();
        for(Specs ele : specses){
            specsHashMap.put(ele.getSpecsId(),ele);
        }

        ArrayList<ShowShopCartsVO> ShowShopCartsVOs = CollUtil.newArrayList();
        for(int i = 0 ; i < shopCarts.size() ; i++){
            ShopCart shopCart = shopCarts.get(i);
            ShowShopCartsVO showShopCartsVO = BeanUtil.copyProperties(shopCart, ShowShopCartsVO.class);
            List<Long> bean = null;
            if(specHashmap.containsKey(shopCart.getSkuId())){
                Skus skus = specHashmap.get(shopCart.getSkuId());
                showShopCartsVO.setPrice(skus.getOldPrice());
                showShopCartsVO.setNowOriginalPrice(skus.getPrice());
                showShopCartsVO.setNowPrice(skus.getPrice());
                //商品id
                showShopCartsVO.setId(skus.getGoodsId());
                //设置商品属性
                if(detailHashMap.containsKey(skus.getGoodsId())){
                    showShopCartsVO.setAttrsText(detailHashMap.get(skus.getGoodsId()));
                }
                bean = JSONUtil.toBean(skus.getSpecsIdList(), new TypeReference<List<Long>>() {
                }, false);

            }

            //商品规格列表
            List<String> showSpecs = CollUtil.newArrayList();
            for(int j = 0 ; bean != null && j < bean.size() ; j++){
                Long ele = bean.get(j);
                if(specsHashMap.containsKey(ele)){
                    showSpecs.add(specsHashMap.get(ele).getSpecsDesc());
                }
            }
            showShopCartsVO.setSpecs(showSpecs);
            if(goodsHashMap.containsKey(shopCart.getGoodsId())){
                Goods goods1 = goodsHashMap.get(shopCart.getGoodsId());
                //商品库存
                showShopCartsVO.setStock(goods1.getInventory());
                showShopCartsVO.setDiscount(goods1.getDiscount());
                showShopCartsVO.setName(goods1.getName());
            }

            ShowShopCartsVOs.add(showShopCartsVO);
        }
        return ShowShopCartsVOs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShowShopCartsVO addShopCart(MergeCartDTO mergeCartDTOs) {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<Goods>();
        LambdaQueryWrapper<Skus> skusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取sku表数据
        skusLambdaQueryWrapper.eq(Skus::getId,mergeCartDTOs.getSkuId());
        Skus skuses = skusMapper.selectOne(skusLambdaQueryWrapper);
        //获取商品表信息
        goodsLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(skuses),Goods::getId,skuses.getGoodsId());
        Goods goods = goodsMapper.selectOne(goodsLambdaQueryWrapper);
        //查出所有商品规格id
            String specsIdList = skuses.getSpecsIdList();
            List<Integer> specs = JSONUtil.toBean(specsIdList, new TypeReference<List<Integer>>() {
            }, false);

        //设置商品属性
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(Details::getGoodsId,goods.getId());
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);
        String join = null;
        for(Details details1 : details) {
            join = StrUtil.join(join, details1.getName() + " " + details1.getValue());
        }

        //查出所有商品规格
        LambdaQueryWrapper<Specs> specsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        specsLambdaQueryWrapper.in(CollUtil.isNotEmpty(specs),Specs::getSpecsId,specs);
        List<Specs> specses = specsMapper.selectList(specsLambdaQueryWrapper);
        HashMap<Long, Specs> specsHashMap = MapUtil.newHashMap();
        for(Specs ele : specses){
            specsHashMap.put(ele.getSpecsId(),ele);
        }

        ShopCart shopCart = BeanUtil.copyProperties(mergeCartDTOs, ShopCart.class);
        Float discount = goods.getDiscount();

        shopCart.setNowPrice(skuses.getPrice());
        shopCart.setNowOriginalPrice(skuses.getPrice());
        shopCart.setUserId(BaseContext.getCurrentId());
        shopCart.setAttrsText(join);
        shopCart.setGoodsId(skuses.getGoodsId());

        ShowShopCartsVO showShopCartsVO = BeanUtil.copyProperties(shopCart, ShowShopCartsVO.class);
        showShopCartsVO.setDiscount(discount);
        showShopCartsVO.setPrice(skuses.getOldPrice());
        //商品id
        showShopCartsVO.setId(skuses.getGoodsId());
        List<Long> bean = JSONUtil.toBean(skuses.getSpecsIdList(), new TypeReference<List<Long>>() {
        }, false);

        showShopCartsVO.setAttrsText(join);
        //商品规格列表
        List<String> showSpecs = CollUtil.newArrayList();
        for(Long ele : bean){
            if(specsHashMap.containsKey(ele)){
                showSpecs.add(specsHashMap.get(ele).getSpecsDesc());
            }
        }
        showShopCartsVO.setSpecs(showSpecs);

        //商品库存
        showShopCartsVO.setStock(goods.getInventory());
        showShopCartsVO.setName(goods.getName());

    if(!save(shopCart)){
        //加入失败
        return null;
    }
    return showShopCartsVO;
}

    @Override
    public R<String> deleteShopCart(List<Integer> ids) {
        if(this.lambdaUpdate().eq(ShopCart::getUserId, BaseContext.getCurrentId())
                .in(CollUtil.isNotEmpty(ids), ShopCart::getSkuId, ids)
                .remove()
        ){
            return R.success("删除成功");
        }else {
            return R.error(ERROR,"删除失败");
        }

    }

    @Override
    public ShowShopCartsVO modifyGood(long id, MergeCartDTO mergeCartDTOs) {
        //先更新购物车数据
        ShopCart shopCart = this.lambdaQuery().eq(ShopCart::getSkuId, id).one();
        if(mergeCartDTOs.getSelected() != null){
            shopCart.setSelected(mergeCartDTOs.getSelected());
        }
        if(mergeCartDTOs.getCount() != null && mergeCartDTOs.getCount() > 0){
            shopCart.setCount(mergeCartDTOs.getCount());
        }

        //生成展示数据
        ShowShopCartsVO showShopCartsVO = BeanUtil.copyProperties(shopCart, ShowShopCartsVO.class);

        LambdaQueryWrapper<Skus> skusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skusLambdaQueryWrapper.eq(Skus::getId,id);
        Skus skus = skusMapper.selectOne(skusLambdaQueryWrapper);

        showShopCartsVO.setPrice(skus.getOldPrice());
        //商品id
        showShopCartsVO.setId(skus.getGoodsId());

        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(Goods::getId,skus.getGoodsId());
        Goods goods = goodsMapper.selectOne(goodsLambdaQueryWrapper);


        //商品库存
        showShopCartsVO.setStock(goods.getInventory());
        showShopCartsVO.setDiscount(goods.getDiscount());
        showShopCartsVO.setName(goods.getName());
        showShopCartsVO.setPrice(skus.getOldPrice());

        //获取商品规格id
        List<Integer> bean = JSONUtil.toBean(skus.getSpecsIdList(), new TypeReference<List<Integer>>() {
        }, false);

        //查出所有商品规格
        LambdaQueryWrapper<Specs> specsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        specsLambdaQueryWrapper.in(CollUtil.isNotEmpty(bean),Specs::getSpecsId,bean);
        List<Specs> specs = specsMapper.selectList(specsLambdaQueryWrapper);
        List<String> showSpecs = CollUtil.newArrayList();

        for(Specs specs1 : specs){
            showSpecs.add(specs1.getSpecsDesc());
        }
        showShopCartsVO.setSpecs(showSpecs);
        if(!this.lambdaUpdate().update(shopCart)){
            return null;
        }
        return showShopCartsVO;
    }

    @Override
    public R<String> AllSelected(AllSelectedDTO allSelectedDTO) {
        List<Long> skuIds = allSelectedDTO.getIds().stream().map(Long::valueOf).collect(Collectors.toList());
        if(
            this.lambdaUpdate().in(CollUtil.isNotEmpty(skuIds),ShopCart::getSkuId,skuIds)
                    .set(ShopCart::getSelected,allSelectedDTO.getSelected())
                    .update()
        ){
            return R.success("操作成功");
        }
        return R.error(ERROR,"操作失败");

    }
}
